package com.csw.mybatisSpringboot.util;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;

/**
 * 在线时间戳转换工具  http://shijianchuo.wiicha.com/
 * 雪花算法能保证69年不重复
 * twitter的snowflake算法 -- java实现
 *
 * @Autowired private SnowFlakeIdUtil snowFlakeIdUtil;
 * <p>
 * //同一个机器上是单例【相当于上了一把锁一个一个进】，不同机器上分布式加锁或者用网卡地址区分
 * 相同服务之间最好指定不同的数据中心id和机器id
 * //    snowflake.datacenterId = 3
 * //    snowflake.machineId = 4
 * //    @Value("${snowflake.datacenterId}")
 * //    private long datacenterIdStr;
 * //
 * //    @Value("${snowflake.machineId}")
 * //    private long machineIdStr;
 * //
 * //    @Bean
 * //    public SnowFlakeIdUtil() {
 * //        //通过当前物理网卡地址获取datacenterId
 * //        this.datacenterId = datacenterIdStr;
 * //        //物理网卡地址+jvm进程pi获取workerId
 * //        this.machineId = machineIdStr;
 * //    }
 */
@Component
public class SnowFlakeIdUtil {

    /**
     * 起始的时间戳
     */
    private final long START_STMP = 1480166465631L;

    /*
     * 每一部分占用的位数
     */
    /**
     * 序列号占用的位数
     */
    private final long SEQUENCE_BIT = 12;
    /**
     * 机器标识占用的位数
     */
    private final long MACHINE_BIT = 5;
    /**
     * 数据中心占用的位数 数据中心占用的位数默认是5位建议用4位【时间戳就会变为42位】，可以使用139年】
     */
    private final long DATACENTER_BIT = 4;

    /**
     * 每一部分的最大值
     */
    private final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);
    /**
     * 支持的最大机器id，结果是31(这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)
     */
    private final long maxMachineId = -1L ^ (-1L << MACHINE_BIT);

    /**
     * 支持的最大数据标识id，结果是7
     */
    private final long maxDatacenterId = -1L ^ (-1L << DATACENTER_BIT);

    /**
     * 每一部分向左的位移
     */
    private final long MACHINE_LEFT = SEQUENCE_BIT;
    private final long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
    /**
     * 数据中心
     */
    private final long datacenterId;
    /**
     * //机器标识
     */
    private final long machineId;
    /**
     * //序列号
     */
    private long sequence = 0L;
    /**
     * 上一次时间戳
     */
    private long lastStmp = -1L;

    public SnowFlakeIdUtil(long datacenterId, long machineId) {
        if (datacenterId <= maxDatacenterId && datacenterId >= 0L) {
            if (machineId <= maxMachineId && machineId >= 0L) {
                this.datacenterId = datacenterId;
                this.machineId = machineId;
            } else {
                throw new IllegalArgumentException(StrUtil.format("datacenter Id can't be greater than {} or less than 0", new Object[]{maxMachineId}));
            }
        } else {
            throw new IllegalArgumentException(StrUtil.format("worker Id can't be greater than {} or less than 0", new Object[]{maxDatacenterId}));
        }

    }

    public SnowFlakeIdUtil() {
        //通过当前物理网卡地址获取datacenterId
        this.datacenterId = getDatacenterId(maxDatacenterId);
        //物理网卡地址+jvm进程pi获取workerId
        this.machineId = getMaxMachineId(datacenterId, maxMachineId);
    }


    /**
     * 产生下一个ID
     */
    public synchronized long nextId() {
        long currStmp = getNewstmp();
        if (currStmp < lastStmp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }

        if (currStmp == lastStmp) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStmp = getNextMill();
            }
        } else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }

        lastStmp = currStmp;
        /*
         * //时间戳部分
         * //数据中心部分
         * //机器标识部分
         * //序列号部分
         */
        return (currStmp - START_STMP) << TIMESTMP_LEFT
                | datacenterId << DATACENTER_LEFT
                | machineId << MACHINE_LEFT
                | sequence;
    }

    private long getNextMill() {
        long mill = getNewstmp();
        while (mill <= lastStmp) {
            mill = getNewstmp();
        }
        return mill;
    }

    private long getNewstmp() {
        return System.currentTimeMillis();
    }

    protected long getDatacenterId(long maxDatacenterId) {
        long id = 0L;
        try {
            //获取本机(或者服务器ip地址)
            //DESKTOP-123SDAD/192.168.1.87
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            //一般不是null会进入else
            if (network == null) {
                id = 1L;
            } else {
                //获取物理网卡地址
                byte[] mac = network.getHardwareAddress();
                if (null != mac) {
                    id = ((0x000000FF & (long) mac[mac.length - 2]) | (0x0000FF00 & (((long) mac[mac.length - 1]) << 8))) >> 6;
                    id = id % (maxDatacenterId + 1);
                }
            }
        } catch (Exception e) {
//            log.warn(" getDatacenterId: " + e.getMessage());
        }
        return id;
    }

    /**
     * 获取 maxWorkerId
     */
    protected long getMaxMachineId(long datacenterId, long maxMachineId) {
        StringBuilder mpid = new StringBuilder();
        mpid.append(datacenterId);
        //获取jvm进程信息
        String name = ManagementFactory.getRuntimeMXBean().getName();
        if (StringUtils.isNotBlank(name)) {
            /*
             * 获取进程PID
             */
            mpid.append(name.split(StringPool.AT)[0]);
        }
        /*
         * MAC + PID 的 hashcode 获取16个低位
         */
        return (mpid.toString().hashCode() & 0xffff) % (maxMachineId + 1);
    }
}